import { useCallback, useRef, useState } from 'react'

export default function useEquityHistory (trader) {
  const [history, setHistory] = useState([])
  const historyRef = useRef([])

  const record = useCallback((timestamp, equityOverride) => {
    if (!trader) return
    const equity = equityOverride ?? ((trader.cash ?? 0) + (trader.position ?? 0))
    const point = {
      timestamp: timestamp ?? Date.now(),
      equity
    }
    historyRef.current = [...historyRef.current, point]
    setHistory(historyRef.current)
  }, [trader])

  const reset = useCallback(() => {
    historyRef.current = []
    setHistory([])
  }, [])

  return {
    history,
    record,
    reset,
    historyRef
  }
}
